﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace IQKS.AWP.EmailManager
{
    public partial class EmailManagerService : ServiceBase
    {
        private Timer timerEmailSvc = null;
        public  EmailServerBO objEmailServerBO = null;

        //[Conditional("DEBUG_SERVICE")]
        //private static void DebugMode()
        //{
        //    Debugger.Break();
        //}
         /// <summary>
        /// Email Manager Service - Initialize Component
         /// </summary>
        public EmailManagerService()
        {
            try
            {
                InitializeComponent();
                GetEmailServer();
            }
            catch (Exception ex)
            {
                WriteErrorLog(ex);
            }
           
        }

        /// <summary>
        /// Email Manager Service - On Start
        /// </summary>
        /// <param name="args"></param>
        protected override void OnStart(string[] args)
        {
            WriteErrorLog("Email Manager window service is started");
            timerEmailSvc = new Timer();
            //this.timerEmailSvc.Interval = 180000; // 3 mins (interval is in seconds)    [//60000; // 1 min]      [//300000; // every 5 mins]
            this.timerEmailSvc.Interval = Convert.ToDouble(ConfigurationManager.AppSettings["EmailManagerServiceInterval"].ToString());
            this.timerEmailSvc.Elapsed += new ElapsedEventHandler(this.timerEmailSvc_Elapsed);
            this.timerEmailSvc.Enabled = true;
            
        }

        private void timerEmailSvc_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                this.timerEmailSvc.Enabled = false;
                //WriteErrorLog("Email Manager window service - timerEmailSvc_Elapsed event process is started.");
                //DebugMode();
                GetEmailServer();
                GetAndSendEmailsInQueue();
                //WriteErrorLog("Email Manager window service - timerEmailSvc_Elapsed event process is finished.");
                this.timerEmailSvc.Enabled = true;
            }
            catch (Exception ex)
            {
                
                this.timerEmailSvc.Enabled = true;
                WriteErrorLog(ex);
            }
            finally
            {
                this.timerEmailSvc.Enabled = true;
            }
        }

        /// <summary>
        /// Gets and Sends Emails In  EmailQueue table
        /// </summary>
        private  void GetAndSendEmailsInQueue()
        {
            EmailManagerBO objEmailManagerBO;
            string ToEmailID, CcEmailID, Subject, Message = string.Empty;
            string AttachmentPaths = string.Empty;
            DataSet dsEmailQueue = new EmailManagerDAL().GetRecordsForSendingEmails();
            if (dsEmailQueue.Tables.Count > 0)
            {
                for (int i = 0; i < dsEmailQueue.Tables[0].Rows.Count; i++)
                {
                    int EmailQueueID = Convert.ToInt32(dsEmailQueue.Tables[0].Rows[i]["EmailQueueID"].ToString());
                    objEmailManagerBO = new EmailManagerBO();
                    objEmailManagerBO.EmailQueueID = EmailQueueID;

                    try
                    {
                        ToEmailID = dsEmailQueue.Tables[0].Rows[i]["UserIDTo"].ToString();
                        CcEmailID = dsEmailQueue.Tables[0].Rows[i]["UserIDCC"].ToString();
                        Subject = dsEmailQueue.Tables[0].Rows[i]["EmailSubject"].ToString();
                        Message = dsEmailQueue.Tables[0].Rows[i]["EmailBody"].ToString();
                        AttachmentPaths = dsEmailQueue.Tables[0].Rows[i]["AttachmentPaths"].ToString();
                        //bjp added as on 29-12-2016 for sending email with attachments
                        if (AttachmentPaths != "" && AttachmentPaths != string.Empty)
                        {
                            SendMail(ToEmailID, CcEmailID, Subject, Message, AttachmentPaths);
                        }
                        else
                        {
                            SendMail(ToEmailID, CcEmailID, Subject, Message);
                        }
                        objEmailManagerBO.EmailSentCode = "SENT";
                        objEmailManagerBO.EmailErrorMsg = "Mail Sent Successfully.";
                    }
                    catch (Exception ex)
                    {
                        objEmailManagerBO.EmailSentCode = "ERROR";
                        objEmailManagerBO.EmailErrorMsg = ex.Message;
                        WriteErrorLog(ex);
                    }
                    finally
                    {
                        string strReturnValue = (string)new EmailManagerDAL().SetEmailSentStatus(objEmailManagerBO);
                        if (strReturnValue == "ERROR")
                        {
                            strReturnValue = "Error while updating Email Sent Status";
                            WriteErrorLog(strReturnValue);
                        }
                    }
                }
            }
        }

        protected override void OnStop()
        {
            timerEmailSvc.Enabled = false;
            WriteErrorLog("Email Manager window service is stopped");
        }

        /// <summary>
        /// Send emails 
        /// </summary>
        /// <param name="ToEmailID">To Email ID</param>
        /// <param name="CcEmailID">CC Email ID</param>
        /// <param name="Subject">Email Subject</param>
        /// <param name="Message">Email Message body</param>
        public void SendMail(string ToEmailID, string CcEmailID, string Subject, string Message)
        {
            GetEmailServer();
            //ToEmailID = "shrikant.bhosale@axisvation.com";
            //CcEmailID = "nilesh.sawant@axisvation.com";
            //string FromMailID = "contact@axisvation.com"; //"admin@iqkonsumerstrategiez.com";

            string FromMailID = objEmailServerBO.SMTPServerEmail; //"admin@iqkonsumerstrategiez.com";
            SmtpClient smtpClient = null;
            MailAddress fromMailAddress = new MailAddress(FromMailID);
            //MailAddress toMailAddress = new MailAddress(ToEmailID);
            //MailAddress ccMailAddress = new MailAddress(CcEmailID);

            MailMessage mailMessage = new MailMessage();
            mailMessage.From = fromMailAddress;
            if (ToEmailID.EndsWith(","))
            {
                ToEmailID = ToEmailID.Substring(0, ToEmailID.Length - 1);
            }
            if (CcEmailID.EndsWith(","))
            {
                CcEmailID = CcEmailID.Substring(0, CcEmailID.Length - 1);
            }
            mailMessage.To.Add(ToEmailID);
            if (CcEmailID != "" && CcEmailID != String.Empty)
            {
                mailMessage.CC.Add(CcEmailID);
            }           
            mailMessage.Body = Message;
            mailMessage.Subject = Subject;

            //smtpClient = new SmtpClient(objEmailServerBO.SMTPServer);
            //smtpClient.Credentials = new System.Net.NetworkCredential(objEmailServerBO.SMTPServerEmail, objEmailServerBO.SMTPServerPassword);
            int smtpPort = Convert.ToInt32(ConfigurationManager.AppSettings["SMTPPort"].ToString());
            smtpClient = new SmtpClient(objEmailServerBO.SMTPServer, smtpPort)
            {
                Credentials = new System.Net.NetworkCredential(objEmailServerBO.SMTPServerEmail, objEmailServerBO.SMTPServerPassword),
                EnableSsl = true
            };
            mailMessage.IsBodyHtml = true;
            smtpClient.Send(mailMessage);
        }
        //bjp added for attachment email send
        public void SendMail(string ToEmailID, string CcEmailID, string Subject, string Message, string AttachmentPaths)
        {
            GetEmailServer();
            //ToEmailID = "shrikant.bhosale@axisvation.com";
            //CcEmailID = "nilesh.sawant@axisvation.com";
            //string FromMailID = "contact@axisvation.com"; //"admin@iqkonsumerstrategiez.com";


            string FromMailID = objEmailServerBO.SMTPServerEmail; //"admin@iqkonsumerstrategiez.com";
            SmtpClient smtpClient = null;
            MailAddress fromMailAddress = new MailAddress(FromMailID);
            //MailAddress toMailAddress = new MailAddress(ToEmailID);
            //MailAddress ccMailAddress = new MailAddress(CcEmailID);

            MailMessage mailMessage = new MailMessage();
            mailMessage.From = fromMailAddress;
            if (ToEmailID.EndsWith(","))
            {
                ToEmailID = ToEmailID.Substring(0, ToEmailID.Length - 1);
            }
            if (CcEmailID.EndsWith(","))
            {
                CcEmailID = CcEmailID.Substring(0, CcEmailID.Length - 1);
            }
            mailMessage.To.Add(ToEmailID);
            if (CcEmailID != "" && CcEmailID != String.Empty)
            {
                mailMessage.CC.Add(CcEmailID);
            }
            mailMessage.Body = Message;
            mailMessage.Subject = Subject;
            if (AttachmentPaths != "" && AttachmentPaths != String.Empty)
            {
                Attachment atch;
                string[] ap = AttachmentPaths.Split(';');
                string vFinalFile = string.Empty;
                for (int i = 0; i < ap.Length; i++)
                {
                    vFinalFile = string.Empty;
                    vFinalFile = ap[i].Trim().Replace("~", ConfigurationManager.AppSettings["AttachmentFolder"]);
                    //vFinalFile = vFinalFile.Replace("//","\\");
                    if (vFinalFile != "" && vFinalFile != String.Empty)
                    {
                        atch = new Attachment(vFinalFile);
                        mailMessage.Attachments.Add(atch);
                    }
                    WriteErrorLog("Path attached : " + vFinalFile);
                }
            }
            WriteErrorLog("Attechment done");
            //smtpClient = new SmtpClient(objEmailServerBO.SMTPServer);
            //smtpClient.Credentials = new System.Net.NetworkCredential(objEmailServerBO.SMTPServerEmail, objEmailServerBO.SMTPServerPassword);
            int smtpPort = Convert.ToInt32(ConfigurationManager.AppSettings["SMTPPort"].ToString());
            smtpClient = new SmtpClient(objEmailServerBO.SMTPServer, smtpPort)
            {
                Credentials = new System.Net.NetworkCredential(objEmailServerBO.SMTPServerEmail, objEmailServerBO.SMTPServerPassword),
                EnableSsl = true
            };
            mailMessage.IsBodyHtml = true;
            smtpClient.Send(mailMessage);
            WriteErrorLog("Message Sent");
        }

        /// <summary>
        /// Get Email Server details.
        /// </summary>
        private  void GetEmailServer()
        {
            if (objEmailServerBO == null)
            {
                objEmailServerBO = new EmailManagerDAL().GetEmailServer();
            }
        }

        /// <summary>
        /// Write Error Log for exceptions
        /// </summary>
        /// <param name="ex"></param>
        public static void WriteErrorLog(Exception ex)
        {
            StreamWriter sw = null;
            try
            {
                sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\LogFile.txt", true);
                sw.WriteLine(DateTime.Now.ToString() + ": " + ex.Source.ToString().Trim() + "; " + ex.Message.ToString().Trim());
                sw.Flush();
                sw.Close();
            }
            catch
            {
            }
        }

        /// <summary>
        ///  Write Error Log for events/SQL/Custom errors.
        /// </summary>
        /// <param name="Message"></param>
        public static void WriteErrorLog(string Message)
        {
            StreamWriter sw = null;
            try
            {
                sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\LogFile.txt", true);
                sw.WriteLine(DateTime.Now.ToString() + ": " + Message);
                sw.Flush();
                sw.Close();
            }
            catch
            {
            }
        }
    }
}
